#!/bin/bash

# Funi Web MCP 增强部署脚本
# 使用方法: ./deploy-enhanced.sh [环境] [选项]
# 环境: dev, staging, prod
# 选项: --rebuild, --logs, --status, --cleanup

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 图标定义
SUCCESS="✅"
ERROR="❌"
WARNING="⚠️"
INFO="ℹ️"
ROCKET="🚀"
STOP="🛑"
BUILD="🔨"
CHECK="🔍"

# 打印带颜色的消息
print_message() {
    local color=$1
    local icon=$2
    local message=$3
    echo -e "${color}${icon} ${message}${NC}"
}

# 检查依赖
check_dependencies() {
    print_message $BLUE $INFO "检查依赖..."
    
    if ! command -v docker &> /dev/null; then
        print_message $RED $ERROR "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_message $RED $ERROR "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    print_message $GREEN $SUCCESS "依赖检查通过"
}

# 环境配置
setup_environment() {
    local env=${1:-prod}
    print_message $BLUE $INFO "设置环境: $env"
    
    # 复制环境配置文件
    if [ ! -f .env ]; then
        if [ -f .env.example ]; then
            cp .env.example .env
            print_message $YELLOW $WARNING "已创建 .env 文件，请根据需要修改配置"
        else
            print_message $RED $ERROR "未找到 .env.example 文件"
            exit 1
        fi
    fi
    
    # 根据环境设置不同的配置
    case $env in
        dev)
            export NODE_ENV=development
            export MCP_PORT=3001
            ;;
        staging)
            export NODE_ENV=staging
            export MCP_PORT=3002
            ;;
        prod)
            export NODE_ENV=production
            export MCP_PORT=3000
            ;;
        *)
            print_message $RED $ERROR "未知环境: $env"
            exit 1
            ;;
    esac
}

# 构建和部署
deploy() {
    local rebuild=$1
    
    print_message $BLUE $ROCKET "开始部署 Funi Web MCP 服务..."
    
    # 停止现有服务
    print_message $BLUE $STOP "停止现有服务..."
    docker-compose down || true
    
    # 是否重新构建
    if [ "$rebuild" = "true" ]; then
        print_message $BLUE $BUILD "重新构建镜像..."
        docker-compose build --no-cache
    else
        print_message $BLUE $BUILD "构建镜像..."
        docker-compose build
    fi
    
    # 启动服务
    print_message $BLUE $ROCKET "启动服务..."
    docker-compose up -d
    
    # 等待服务启动
    print_message $BLUE $INFO "等待服务启动..."
    sleep 15
    
    # 健康检查
    health_check
    
    # 显示配置信息
    show_config_info
}

# 健康检查
health_check() {
    print_message $BLUE $CHECK "检查服务状态..."
    
    local max_attempts=10
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -f http://localhost:${MCP_PORT:-3000}/mcp > /dev/null 2>&1; then
            print_message $GREEN $SUCCESS "服务部署成功！"
            print_message $GREEN $INFO "服务地址: http://localhost:${MCP_PORT:-3000}/mcp"
            return 0
        fi
        
        print_message $YELLOW $WARNING "尝试 $attempt/$max_attempts - 服务尚未就绪，等待5秒..."
        sleep 5
        ((attempt++))
    done
    
    print_message $RED $ERROR "服务部署失败，请检查日志"
    docker-compose logs
    exit 1
}

# 显示配置信息
show_config_info() {
    print_message $GREEN $SUCCESS "部署完成！"
    echo ""
    print_message $BLUE $INFO "🔧 Trae IDE 配置信息："
    echo ""
    echo "=== 本地开发配置 ==="
    echo '{'
    echo '  "mcpServers": {'
    echo '    "FuniWebMCP": {'
    echo '      "transport": {'
    echo '        "type": "http",'
    echo '        "baseUrl": "http://localhost:'${MCP_PORT:-3000}'",'
    echo '        "endpoint": "/mcp"'
    echo '      }'
    echo '    }'
    echo '  }'
    echo '}'
    echo ""
    echo "=== 生产环境配置 ==="
    echo '{'
    echo '  "mcpServers": {'
    echo '    "FuniWebMCP": {'
    echo '      "transport": {'
    echo '        "type": "http",'
    echo '        "baseUrl": "https://your-domain.com",'
    echo '        "endpoint": "/mcp"'
    echo '      }'
    echo '    }'
    echo '  }'
    echo '}'
    echo ""
    print_message $YELLOW $WARNING "注意事项："
    echo "1. 确保防火墙允许端口 ${MCP_PORT:-3000} 的访问"
    echo "2. 生产环境建议使用 HTTPS 和域名"
    echo "3. 可以通过 Nginx 反向代理提供负载均衡"
    echo "4. 建议配置 API 密钥进行身份验证"
}

# 显示状态
show_status() {
    print_message $BLUE $INFO "服务状态:"
    docker-compose ps
    
    print_message $BLUE $INFO "容器资源使用情况:"
    docker stats --no-stream FuniA0Mcp 2>/dev/null || echo "容器未运行"
    
    print_message $BLUE $INFO "服务健康状态:"
    if curl -f http://localhost:${MCP_PORT:-3000}/mcp > /dev/null 2>&1; then
        print_message $GREEN $SUCCESS "服务运行正常"
    else
        print_message $RED $ERROR "服务无法访问"
    fi
}

# 显示日志
show_logs() {
    print_message $BLUE $INFO "显示服务日志:"
    docker-compose logs -f --tail=100
}

# 清理
cleanup() {
    print_message $BLUE $INFO "清理资源..."
    docker-compose down
    docker system prune -f
    print_message $GREEN $SUCCESS "清理完成"
}

# 主函数
main() {
    local env="prod"
    local rebuild=false
    local action="deploy"
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            dev|staging|prod)
                env="$1"
                shift
                ;;
            --rebuild)
                rebuild=true
                shift
                ;;
            --logs)
                action="logs"
                shift
                ;;
            --status)
                action="status"
                shift
                ;;
            --cleanup)
                action="cleanup"
                shift
                ;;
            --help|-h)
                echo "使用方法: $0 [环境] [选项]"
                echo "环境: dev, staging, prod (默认: prod)"
                echo "选项:"
                echo "  --rebuild  重新构建镜像"
                echo "  --logs     显示日志"
                echo "  --status   显示状态"
                echo "  --cleanup  清理资源"
                echo "  --help     显示帮助"
                exit 0
                ;;
            *)
                print_message $RED $ERROR "未知参数: $1"
                exit 1
                ;;
        esac
    done
    
    # 执行操作
    case $action in
        deploy)
            check_dependencies
            setup_environment $env
            deploy $rebuild
            ;;
        logs)
            show_logs
            ;;
        status)
            show_status
            ;;
        cleanup)
            cleanup
            ;;
    esac
}

# 捕获中断信号
trap 'print_message $YELLOW $WARNING "部署被中断"; exit 1' INT TERM

# 运行主函数
main "$@"
